import { View } from '@tarojs/components'
import { useRef, useState, useMemo, useEffect } from 'react'
import './index.scss'
import Taro from '@tarojs/taro'

interface CustomSwiperProps {
  pauseTime?: number
  swiperList: Record<string, any>[]
  children: (props: { item: Record<string, any>; index: number; isActive: boolean }) => JSX.Element
}

export default function CustomSwiper({ pauseTime = 500, swiperList, children }: CustomSwiperProps) {
  const [curIdx, setCurIdx] = useState(0)
  const [translateY, setTranslateY] = useState(0)
  const touchStartY = useRef(0)
  const touchMoveY = useRef(0)
  const isAnimating = useRef(false) // 节流标志
  const timer = useRef<NodeJS.Timeout>()

  // 只渲染当前项及其前后各一项
  const visibleItems = useMemo(() => {
    const start = Math.max(0, curIdx - 1)
    const end = Math.min(swiperList.length, curIdx + 2)
    return swiperList.slice(start, end).map((item, index) => ({
      data: { ...item },
      virtualIndex: start + index,
    }))
  }, [swiperList, curIdx])

  // 计算当前项的位置
  const basePosition = useMemo(() => {
    return -curIdx * 100
  }, [curIdx])

  const handleTouchStart = (e: any) => {
    if (isAnimating.current) return
    touchStartY.current = e.touches[0].clientY
    touchMoveY.current = 0
  }

  const handleTouchMove = (e: any) => {
    if (isAnimating.current) return
    e.preventDefault?.() // 阻止默认滚动
    e.stopPropagation?.()
    touchMoveY.current = e.touches[0].clientY
    const distance = touchMoveY.current - touchStartY.current
    if ((curIdx === 0 && distance > 0) || (curIdx === swiperList.length - 1 && distance < 0)) {
      setTranslateY(distance * 0.3)
      return
    }

    setTranslateY(distance)
  }

  const handleTouchEnd = () => {
    if (isAnimating.current) return

    const distance = touchMoveY.current - touchStartY.current
    if (Math.abs(distance) > 100 && touchMoveY.current !== 0) {
      isAnimating.current = true // 开始切换时设置动画状态
      if (distance > 0 && curIdx > 0) {
        setCurIdx(curIdx - 1)
      } else if (distance < 0 && curIdx < swiperList.length - 1) {
        setCurIdx(curIdx + 1)
      }
      // 等待动画完成后重置状态
      if (timer.current) {
        clearTimeout(timer.current)
      }
      timer.current = setTimeout(() => {
        isAnimating.current = false
      }, pauseTime) // 与过渡动画时间保持一致
    }
    setTranslateY(0)
  }

  // // 自动轮播
  // const handleAutoPlay = () => {
  //     if (curIdx < swiperList.length - 1) {
  //         setCurIdx(curIdx + 1);
  //     } else {
  //         setCurIdx(0);
  //     }
  // };

  // useEffect(() => {
  //     const interval = setInterval(handleAutoPlay, 3000);
  //     return () => clearInterval(interval);
  // }, [curIdx]);

  // useEffect(() => {
  //     const nextIdx = curIdx + 1;
  //     if (nextIdx < swiperList.length && swiperList[nextIdx].src) {
  //         Taro.downloadFile({
  //             url: swiperList[nextIdx].src,
  //             success: () => {
  //                 console.log('下一个视频预加载成功');
  //             },
  //             fail: (err) => {
  //                 console.error('预加载失败:', err);
  //             }
  //         });
  //     }
  // }, [curIdx]);

  return (
    <View className="custom-swiper">
      <View
        className="swiper-content"
        style={{
          height: `${swiperList.length * 100}vh`,
          transform: `translateY(calc(${basePosition}vh + ${translateY}px))`,
          transition: translateY === 0 ? 'transform 0.3s' : 'none',
        }}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        {visibleItems.map(item => (
          <View
            key={item.virtualIndex}
            className="swiper-item"
            style={{
              // background: item.data,
              transform: `translateY(${item.virtualIndex * 100}%)`,
            }}
          >
            {children({
              item: item.data,
              index: item.virtualIndex,
              isActive: item.virtualIndex === curIdx,
            })}
          </View>
        ))}
      </View>
    </View>
  )
}
